package com.szgd.controller.sys;

import com.szgd.controller.BaseController;
import com.szgd.util.FTPUtils;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.StringUtil;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/weboffice")
public class WebofficeController extends BaseController {
    private static Logger logger = Logger.getLogger(WebofficeController.class);

    @RequestMapping("/getTempFile")
    public void getTempFile(HttpServletRequest request, HttpServletResponse response) {
        String templateName = getParam(request, "TPNAME");
        String basePath = request.getServletContext().getRealPath("/");
        String tempPath = basePath + "assets\\template\\";
        String tmpFileName = "JF_shenqing_report.doc";
        if (StringUtil.isNotBlank(templateName)) {
            tmpFileName = templateName;
        }
        //原始模板文件
        File f = new File(tempPath + tmpFileName);
        //复制一个副本供调用
        String copyFileName = UUID.randomUUID() + "";
        File tempDirectoryFile = new File(basePath + "assets\\template\\temp\\");
        if (!tempDirectoryFile.exists()) {
            tempDirectoryFile.mkdirs();
        }
        File copyFile = new File(basePath + "assets\\template\\temp\\" + copyFileName + ".doc");

        try {
            if (!copyFile.exists()) {
                copyFile.createNewFile();
            }
            FileCopyUtils.copy(f, copyFile);    //复制
            OutputStream out;
            //以下输出该副本
            FileInputStream fis = new FileInputStream(copyFile);
            out = response.getOutputStream();

            byte[] buffer = new byte[1024];
            long k = 0;
            while (k < copyFile.length()) {
                int j = fis.read(buffer, 0, 1024);
                k += j;
                out.write(buffer, 0, j);
            }

            fis.close();
            out.close();
            out.flush();
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @RequestMapping("/getOfficeFile")
    public void getOfficeFile(HttpServletRequest request, HttpServletResponse response) {
        String fileID = getParam(request, "fileID");
        String filePath = PropertiesUtil.getFtpPropValue("docPath");
        //复制一个副本供调用
        File copyFile = new File(filePath);

        try {
            OutputStream out;
            //以下输出该副本
            FileInputStream fis = new FileInputStream(copyFile);
            out = response.getOutputStream();

            byte[] buffer = new byte[1024];
            long k = 0;
            while (k < copyFile.length()) {
                int j = fis.read(buffer, 0, 1024);
                k += j;
                out.write(buffer, 0, j);
            }

            fis.close();
            out.close();
            out.flush();
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @RequestMapping("/webUpload")
    public void webUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = getParam(request, "id");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        long startTime = System.currentTimeMillis();
        InputStream in = null;
        List<List<Object>> listob = null;
        MultipartFile file = multipartRequest.getFile("docContent");
        if (file.isEmpty()) {
            throw new Exception("文件不存在！");
        }
        in = file.getInputStream();
        //将文件保存至FTP
        PrintWriter pw = null;
        try {
            pw = response.getWriter();

            FTPUtils ftp = new FTPUtils();
            String hostname = PropertiesUtil.getFtpPropValue("hostname");
            String username = PropertiesUtil.getFtpPropValue("username");
            String password = PropertiesUtil.getFtpPropValue("password");
            Integer port = Integer.valueOf(PropertiesUtil.getFtpPropValue("port"));
            String fileName = UUID.randomUUID().toString().replace("-","").toLowerCase() + ".doc";
            StringBuffer sb = new StringBuffer();
            sb.append("/");
            sb.append("jingfei");
            sb.append("/");
            sb.append(new DateTime().toString("yyyy/MM/dd"));
            sb.append("/");
            sb.append(id);
            sb.append("/");
            ftp.uploadFile(hostname,username,password,port,sb.toString(), fileName, file.getInputStream());

            pw.print("success");
        } catch (FileNotFoundException e) {
            pw.print("failed");
            e.printStackTrace();
        } catch (IOException e) {
            pw.print("failed");
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.flush();
            }
        }
    }
}
